import API_BASE_URL from '../core/config'
import axios, { type AxiosRequestConfig, type AxiosResponse, AxiosError } from 'axios'
import { applyInterceptors } from './axiosInstance'

// 创建 axios 实例
const api = axios.create({
    baseURL: API_BASE_URL,
    timeout: 10000,
})

// 请求拦截器：自动添加 token
api.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        const token = localStorage.getItem('access_token')
        if (token && config.headers) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error: AxiosError) => Promise.reject(error)
)

// 响应拦截器：401 清理本地状态
api.interceptors.response.use(
    (response: AxiosResponse) => response,
    async (error: AxiosError) => {
        if (error.response?.status === 401) {
            localStorage.removeItem('access_token')
            localStorage.removeItem('current_session')
        }
        return Promise.reject(error)
    }
)

applyInterceptors(api)

// ==== 类型定义（与后端保持一致） ====

export interface TokenResponse {
    access_token: string
    token_type: string // 'bearer'
}

export interface UserResponse {
    id: number
    username: string
    full_name: string | null
    role: 'admin' | 'user'
    disabled: boolean
}

export interface UserStatusUpdate {
    disabled: boolean
}

export interface TestSession {
    name: string
    username: string
    password: string
    role: 'admin' | 'user'
    status: '未登录' | '已登录' | '已禁用'
    token?: string
}

export const authApi = {
    // 基础令牌存取
    setToken(token: string) {
        localStorage.setItem('access_token', token)
    },
    clearToken() {
        localStorage.removeItem('access_token')
    },
    getToken(): string | null {
        return localStorage.getItem('access_token')
    },

    // 会话状态存取（用于你的测试面板）
    getSessionState(): TestSession | null {
        const token = this.getToken()
        if (!token) return null
        const sessionStr = localStorage.getItem('current_session')
        if (!sessionStr) return null
        try {
            const session = JSON.parse(sessionStr) as TestSession
            session.token = token
            return session
        } catch {
            return null
        }
    },
    saveSessionState(session: TestSession) {
        if (session.token) this.setToken(session.token)
        localStorage.setItem('current_session', JSON.stringify(session))
    },
    clearSessionState() {
        this.clearToken()
        localStorage.removeItem('current_session')
    },

    // 更新session中的用户信息
    async updateSessionUserInfo() {
        try {
            const userInfo = await this.getCurrentUser()
            const sessionStr = localStorage.getItem('current_session')
            if (sessionStr) {
                const session = JSON.parse(sessionStr)
                session.role = userInfo.role
                session.id = userInfo.id
                session.disabled = userInfo.disabled
                localStorage.setItem('current_session', JSON.stringify(session))
            }
        } catch (error) {
            console.error('更新用户信息失败:', error)
        }
    },

    // 登录（后端: POST /auth/token，表单: username/password）
    async login(username: string, password: string): Promise<TokenResponse> {
        try {
            const form = new URLSearchParams()
            form.append('username', username)
            form.append('password', password)

            const response = await api.post('/auth/token', form, {
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            })

            // 先设置token，然后获取用户信息
            this.setToken(response.data.access_token)

            // 登录成功后获取用户信息
            const userInfo = await this.getCurrentUser()

            const session: TestSession = {
                name: `${username} 的会话`,
                username,
                password,
                role: userInfo.role,
                status: '已登录',
                token: response.data.access_token,
            }
            this.saveSessionState(session)

            return response.data
        } catch (error) {
            console.error('登录失败:', error)
            this.clearSessionState()
            throw error
        }
    },

    // 注册（后端: POST /auth/register，JSON: username/password/full_name?）
    async register(userData: { username: string; password: string; full_name?: string }): Promise<TokenResponse> {
        try {
            const response = await api.post('/auth/register', userData)

            // 先设置token，然后获取用户信息
            this.setToken(response.data.access_token)

            // 注册成功后获取用户信息
            const userInfo = await this.getCurrentUser()

            const session: TestSession = {
                name: `${userData.username} 的会话`,
                username: userData.username,
                password: userData.password,
                role: userInfo.role,
                status: '已登录',
                token: response.data.access_token,
            }
            this.saveSessionState(session)

            return response.data
        } catch (error) {
            console.error('注册失败:', error)
            this.clearSessionState()
            throw error
        }
    },

    // 验证令牌（后端: GET /auth/verify）
    async verifyToken(): Promise<{ valid: boolean }> {
        const response = await api.get('/auth/verify')
        return response.data
    },

    // 修改密码（后端: POST /auth/change-password）
    async changePassword(payload: { current_password: string; new_password: string }): Promise<{ ok: boolean }> {
        const response = await api.post('/auth/change-password', payload)
        return response.data
    },

    // 当前用户（后端: GET /users/me）
    async getCurrentUser(): Promise<UserResponse> {
        const response = await api.get('/users/me')
        return response.data
    },

    // 管理员：获取用户列表（后端: GET /users）
    async getUsers(): Promise<UserResponse[]> {
        const response = await api.get('/users')
        return response.data
    },

    // 管理员：更新用户启用状态（后端: PATCH /users/{id}/status）
    async updateUserStatus(userId: number, disabled: boolean): Promise<{ ok: boolean }> {
        const response = await api.patch(`/users/${userId}/status`, { disabled } as UserStatusUpdate)
        return response.data
    },

    // 管理员：删除用户（后端: DELETE /users/{id}）
    async deleteUser(userId: number): Promise<{ ok: boolean }> {
        const response = await api.delete(`/users/${userId}`)
        return response.data
    },

    // 管理员：创建用户（后端: POST /users）
    async createUser(userData: { username: string; password: string; role?: string; disabled?: boolean }): Promise<UserResponse> {
        const response = await api.post('/users', userData)
        return response.data
    },

    // 管理页面（后端: GET /pages/admin）
    async getAdminPage(): Promise<{ message: string }> {
        const response = await api.get('/pages/admin')
        return response.data
    },

    // 个人中心页面（后端: GET /pages/profile）
    async getProfilePage(): Promise<{ message: string; username: string }> {
        const response = await api.get('/pages/profile')
        return response.data
    },

    // 管理员操作（后端: POST /pages/admin/actions）
    async adminAction(): Promise<{ message: string }> {
        const response = await api.post('/pages/admin/actions', {})
        return response.data
    },
} 